package com.wu.dms.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wu.dms.cache.UrlCache;
import com.wu.common.convertion.result.Result;
import com.wu.common.convertion.result.Results;
import com.wu.constant.Enum.MinIoNameEnum;
import com.wu.constant.Enum.ResourceTypeAndNameEnum;
import com.wu.constant.Enum.UserStatusEnum;
import com.wu.dms.constant.SexTypeEnum;
import com.wu.dms.dao.entity.User;
import com.wu.dms.dao.mapper.UserMapper;
import com.wu.dms.dao.mapper.UserPunishmentRecordsMapper;
import com.wu.dms.dao.vo.CollectVo;
import com.wu.dms.dto.req.UserStatusReq;
import com.wu.dms.dto.resp.PageResp;
import com.wu.dms.dto.resp.UserDetailResp;
import com.wu.dms.service.UserService;
import com.wu.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Cousin
 * @date 2024/12/26
 * @Description
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final UserMapper userMapper;
    private final UserPunishmentRecordsMapper userPunishmentRecordsMapper;
    @GetMapping()
    public Result<PageResp> queryInPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String userName
    , @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime){
        Page<User> page = Page.of(pageNum, pageSize);
        Page<User> userPage = userService.query().like( "name", userName).page(page);
        List<User> userList = userPage.getRecords();
        AtomicInteger start = new AtomicInteger((pageNum-1) * pageSize + 1);
        List<Map<String, Object>> maps = userList.stream().map(user -> {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", start.getAndAdd(1));
            userMap.put("name", user.getName());
            Date createTime = user.getCreateTime();
            // 定义日期格式化的模板
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 格式化 createTime
            String formattedDate = sdf.format(createTime);
            userMap.put("createTime", formattedDate);
            return userMap;
        }).toList();
        PageResp pageResp = new PageResp();
        pageResp.setData(maps);
        pageResp.setTotal(userPage.getTotal());
        return Results.success(pageResp);
    }
    @GetMapping("/detail")
    public Result<UserDetailResp> queryById(@RequestParam Long id){
        User user = userService.query().eq("id", id).one();
        UserDetailResp userDetailResp = BeanUtil.copyProperties(user, UserDetailResp.class);
        String imageUrl = UrlCache.getUrl(MinIoNameEnum.USER_IMAGE.getBucketName(), id,user.getPic());
        userDetailResp.setPic(imageUrl);
        userDetailResp.setSex(SexTypeEnum.getSexByType(user.getSex()));
        return Results.success(userDetailResp);
    }
    @GetMapping("collection/detail")
    public Result<PageResp> queryCollectionDetails(@RequestParam Long userId,@RequestParam(required = false) Integer pageNum,@RequestParam(required = false) Integer pageSize ,@RequestParam String searchWord
            ,@RequestParam String startDate,@RequestParam String endDate){
        List<CollectVo> collectVos = userMapper.queryUserCollectInPage(userId, pageNum, pageSize, searchWord, startDate, endDate);
        for (CollectVo collectVo : collectVos) {
            collectVo.setResourceType(ResourceTypeAndNameEnum.getNameByType(collectVo.getResourceType()));
        }
        PageResp pageResp =new PageResp();
        pageResp.setData(collectVos);
        pageResp.setTotal(userMapper.countUserCollectInPage(userId,searchWord,startDate,endDate));
        return Results.success(pageResp);
    }
    @PostMapping("updateStatus")
    public Result<Void> updateStatus(@RequestBody UserStatusReq userStatusReq){
        String status = userStatusReq.getStatus();
        Long userId = userStatusReq.getUserId();
        if (UserStatusEnum.NORMAL.getStatus().equals(status)){
            userPunishmentRecordsMapper.delete(userId);
        }else{
            Date now =new Date();
            Integer code = UserStatusEnum.getCodeByStatus(status);
            String banUnit = userStatusReq.getBanUnit();
            Integer banDuration = userStatusReq.getBanDuration();
            String reason = userStatusReq.getReason();
            Date banTime = DateUtil.getTimByUnitAndDuration(now, banUnit, banDuration);
            userPunishmentRecordsMapper.add(userId, code, reason,banTime,now);
        }
        return Results.success( "修改成功");
    }

}